<?php


###########################################################################################
# zencart price options
# kelkoo.php? etc
#
# General options
# description = on,off
# image = on,off
# sef = on,off
# add_vat = on,off
# 
##########################################################################################

set_time_limit(0);
ignore_user_abort();
error_reporting(E_ALL ^ E_NOTICE);
$_SVR = array();

// Path to configure.php file
$path_include = "./includes/";

// Include configuration file
if(!file_exists($path_include . "configure.php")) {
	exit('<HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY><H1>Not Found</H1>Please ensure that this file is in the root directory, or make sure the path to the directory where the configure.php file is located is defined corectly above in $path_include variable</BODY></HTML>');
}
else {
	include_once($path_include . "configure.php");
	include_once($path_include . "application_top.php");
}

// START COMPRESSING
compression_start();

// Datafeed specific settings
$datafeed_separator = "|"; // Possible options are \t or |
// You can also leave this field empty. Please contact us if you are planning to submit the feeds in a different currency
// Define VAT value
$vat_value = 1.25; // 25%

// Description options - possible values on, off
$show_description = ($_GET['description'] == "off") ? "off" : "on";
// Image options - possible values on, off
$show_image = ($_GET['image'] == "off") ? "off" : "on";
// Make URLs SEF
$sef = ($_GET['sef'] == "on") ? "on" : "off";
// Add VAT to prices
$add_vat = ($_GET['add_vat'] == "off") ? "off" : "on";

// Connect to the database
$conn = @mysql_connect(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD);
if (mysql_error()) {
	print "<HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY><H1>Not Found</H1>Connection error. Please check the connection settings. Bye bye...</BODY></HTML>";
	exit;
}
else {
	@mysql_select_db(DB_DATABASE, $conn);
	if (mysql_error()) {
		print "<HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY><H1>Not Found</H1>Connection error. Please check the connection settings. Bye bye...</BODY></HTML>";
		exit;
	}
}

$already_sent = array();

// Detect default language code
//$query_language_code = @mysql_query("SELECT configuration_value FROM " . DB_PREFIX . "configuration WHERE configuration_key = 'DEFAULT_LANGUAGE'");
//$row_language_code = @mysql_fetch_array($query_language_code);

// Detect default language ID
//$query_language_id = @mysql_query("SELECT languages_id FROM " . DB_PREFIX . "languages WHERE code = '" . $row_language_code['configuration_value'] . "'");
$query_language_id = @mysql_query("SELECT languages_id FROM " . DB_PREFIX . "languages WHERE code = 'ES'");
$row_language_id = @mysql_fetch_array($query_language_id);

// Set the main language
$main_language = $row_language_id['languages_id'];

// Detect default currency
$query_currency = @mysql_query("SELECT configuration_value FROM " . DB_PREFIX . "configuration WHERE configuration_key = 'DEFAULT_CURRENCY'");
$row_currency = @mysql_fetch_array($query_currency);

// Detect Vat
$query_vat = @mysql_query("SELECT tax_class_id,tax_rate FROM " . DB_PREFIX . "tax_rates");
$tax_values = array();

while($row_vat = @mysql_fetch_row($query_vat)) {
    $tax_values[$row_vat[0]] = $row_vat[1];
}

// Set the default currency
$datafeed_currency = $row_currency['configuration_value']; 

$prod_table = DB_PREFIX . "products"; // products table
$prod_specials_prices = DB_PREFIX . "specials"; // special prices table
$prod_desc_table = DB_PREFIX . "products_description"; // products descriptions table
$cat_prod_table = DB_PREFIX . "products_to_categories"; // products to categories table
$cat_table = DB_PREFIX . "categories"; // categories table
$cat_desc_table = DB_PREFIX . "categories_description"; // categories descriptions table
$cat_manuf_table = DB_PREFIX . "manufacturers"; // manufacturers table
$prod_attributes_table = DB_PREFIX . "products_attributes"; // products attributes table

// Get all categories
$res_cat = @mysql_query("SELECT * 
FROM $cat_table
LEFT JOIN $cat_desc_table ON ( $cat_table.categories_id = $cat_desc_table.categories_id AND $cat_desc_table.language_id = '$main_language' )");
if (!mysql_error()) {
	while ($field = mysql_fetch_assoc($res_cat)) {
		$CAT_ARR[$field['categories_id']] = $field;
	}
}

// Query database for extracting data. It might be needed to left join the categories table for extracting the category name
$image_field = ($show_image == "on") ? "$prod_table.products_image" : "''";
$description_field = ($show_description == "on") ? "$prod_desc_table.products_description" : "''";

$q = "SELECT DISTINCT $cat_table.categories_id, $cat_manuf_table.manufacturers_name, $prod_table.products_quantity, $prod_table.products_model, $prod_table.products_id, $prod_desc_table.products_name, " . $description_field . ", " . $image_field . ", $prod_table.products_price, $prod_table.products_tax_class_id, $prod_table.products_priced_by_attribute
FROM $prod_table
LEFT JOIN $prod_desc_table ON ( $prod_table.products_id = $prod_desc_table.products_id AND $prod_desc_table.language_id = '$main_language' )
LEFT JOIN $cat_prod_table ON $prod_table.products_id = $cat_prod_table.products_id
LEFT JOIN $cat_table ON $cat_prod_table.categories_id = $cat_table.categories_id
LEFT JOIN $cat_manuf_table ON $prod_table.manufacturers_id = $cat_manuf_table.manufacturers_id
WHERE $cat_table.categories_status > 0 AND $prod_table.products_status > 0
GROUP BY $prod_table.products_id
ORDER BY $cat_table.categories_id DESC";

$r = @mysql_query($q);

// There are no errors so we can continue
if (!mysql_error()) {

	//while ($field = mysql_fetch_assoc($r)) { echo "<pre>";print_r($field);echo "</pre>"; } exit;

	while (list($cat_id, $prod_manufacturer, $prod_quantity, $prod_model, $prod_id, $prod_name, $prod_desc, $prod_image, $prod_price, $tax_class_id, $products_priced_by_attribute) = mysql_fetch_row($r)) {	
		
		// If we've sent this one, skip the rest - this is to ensure that we do not get duplicate products
		if ($already_sent[$prod_id] == 1) continue;
		
		// Clean description
		$prod_desc = clean_description($prod_desc);
		
		// Get category name
		$category_name = get_full_cat($cat_id, $CAT_ARR);
		
		// Clean product name (new lines)
		$prod_name = str_replace("\n", "", strip_tags($prod_name));
		$prod_name = str_replace("\r", "", strip_tags($prod_name));
		$prod_name = str_replace("\t", " ", strip_tags($prod_name));
		
		// Clean product description (Replace new line with <BR>). In order to make sure the code does not contains other HTML code it might be a good ideea to strip_tags()
		$prod_desc = replace_not_in_tags("\n", "<BR />", $prod_desc);
		$prod_desc = str_replace("\n", " ", $prod_desc);		
		$prod_desc = str_replace("\r", "", $prod_desc);
		$prod_desc = str_replace("\t", " ", $prod_desc);
		
		// Clean product names and descriptions (separators)
		if ($datafeed_separator == "\t") {
			// Continue... tabs were already removed
		}
		elseif ($datafeed_separator == "|") {
			$prod_name = str_replace("|", " ", strip_tags($prod_name));
			$prod_desc = str_replace("|", " ", $prod_desc);
		}
		else {
			print "Incorrect columns separator.";
			exit;
		}
		
		if ($sef == "on") {
			$prod_url = function_to_get_seo_url($prod_id, $prod_name, $cat_id, $CAT_ARR);
		}
		else {
			$prod_url = function_to_get_product_url($prod_id, $cat_id);	
		}		
		
		$prod_image = function_to_get_product_image($prod_image);
		
		// Get product price
		$display_normal_price = zen_get_products_base_price($prod_id);
	    $display_special_price = zen_get_products_special_price($prod_id, true);
	    $display_sale_price = zen_get_products_special_price($prod_id, false);
		
		if ($display_sale_price > 0) {
			$prod_price = $display_sale_price;
		}
		elseif ($display_special_price > 0) {
			$prod_price = $display_special_price;
		}
		else {
			$prod_price = $display_normal_price;
		}
		
		// Add VAT to prices
		if ($add_vat == "on") {

            if (isset($tax_values[$tax_class_id])){
			        		//VAT 12% conforme urbano
        		$prod_vat = 1.12;
        		//$prod_price = $prod_price * $vat;
        	}
        	else 
        	    $prod_vat = 1.00;
		}
		
        if ( $prod_quantity > 0 ) {
            $prod_quantity = str_replace($prod_quantity, "1", $prod_quantity);
        } 
        else {
            $prod_quantity = str_replace($prod_quantity, "3", $prod_quantity);
        }  			
		
		// Output the datafeed content
		// Category, Manufacturer, Model, ProdCode, ProdName, ProdDescription, ProdURL, ImageURL, Price, Quantity, Currency
		print 
			$category_name . $datafeed_separator .
			$prod_manufacturer . $datafeed_separator .
			$prod_model . $datafeed_separator .
			$prod_id . $datafeed_separator .
			$prod_name . $datafeed_separator .
			$prod_desc . $datafeed_separator .
			$prod_url . $datafeed_separator .
			$prod_image . $datafeed_separator .
			$prod_price . $datafeed_separator .
            $prod_vat . $datafeed_separator .
            $prod_quantity . $datafeed_separator .
			$datafeed_currency . "\n";
		
		$already_sent[$prod_id] = 1;
	}
}
else {
	print "<HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY><H1>Not Found</H1>Query error: " . mysql_error() . "</BODY></HTML>";
}

// END COMPRESSING
compression_end();

exit;

// Function to return the Product URL based on your product ID
function function_to_get_seo_url($prod_id, $prod_name, $cat_id, $CATEGORY_ARR){
	
	$item_arr = $CATEGORY_ARR[$cat_id];
	$i = 0;
	$cat_str_arr[$i] = build_str_key(html_to_text($item_arr['categories_name']));
	$cat_keys = $item_arr['categories_id'];
	
	while (sizeof($CATEGORY_ARR[$item_arr['parent_id']]) > 0 && is_array($CATEGORY_ARR[$item_arr['parent_id']]) ) {
		
		$i = $i + 1;
		$cat_str_arr[] = build_str_key(html_to_text($CATEGORY_ARR[$item_arr['parent_id']]['categories_name']));		
		$cat_keys = $CATEGORY_ARR[$item_arr['parent_id']]['categories_id'] . "_" . $cat_keys;
		$item_arr = $CATEGORY_ARR[$item_arr['parent_id']];
	}
	
	$cat_str_key = $cat_str_arr[$i] . "-" . $cat_str_arr[$i - 1];
	
	$prod_str_key = build_str_key($prod_name);
	
	if (preg_match("/http\:\/\//", DIR_WS_CATALOG)) {
		return DIR_WS_CATALOG . "product_info/c-" . $cat_str_key . "-" . $cat_keys . "/p-" . $prod_str_key . "-" . $prod_id;
	}
	else {
		return HTTP_SERVER . DIR_WS_CATALOG . "product_info/c-" . $cat_str_key . "-" . $cat_keys . "/p-" . $prod_str_key . "-" . $prod_id;
	}
	
}

// Function to return the Product URL based on your product ID
function function_to_get_product_url($prod_id, $cat_id){
	
	if (preg_match("/http\:\/\//", DIR_WS_CATALOG)) {
		return DIR_WS_CATALOG . "index.php?main_page=product_info&cPath=" . $cat_id . "&products_id=" . $prod_id;
	}
	else {
		return HTTP_SERVER . DIR_WS_CATALOG . "index.php?main_page=product_info&cPath=" . $cat_id . "&products_id=" . $prod_id;
	}	
}

// Function to return the Product Image based on your product image or optionally Product ID
function function_to_get_product_image($prod_image){
	
	if ($prod_image == "") {
		return false;
	}
	elseif (preg_match("/http\:\/\//", $prod_image)) {
		return $prod_image;
	}
	elseif (preg_match("/http\:\/\//", DIR_WS_IMAGES)) {
		return DIR_WS_IMAGES . $prod_image;
	}
	elseif (preg_match("/http\:\/\//", DIR_WS_CATALOG)) {
		return DIR_WS_CATALOG . DIR_WS_IMAGES . $prod_image;
	}
	else {
		return HTTP_SERVER . DIR_WS_CATALOG . DIR_WS_IMAGES . $prod_image;
	}	
}

// Function to get category with full path
function get_full_cat($cat_id, $CATEGORY_ARR) {

	$item_arr = $CATEGORY_ARR[$cat_id];
	$cat_name = $item_arr['categories_name'];
	
	while (sizeof($CATEGORY_ARR[$item_arr['parent_id']]) > 0 && is_array($CATEGORY_ARR[$item_arr['parent_id']]) ) {
		
		$cat_name = $CATEGORY_ARR[$item_arr['parent_id']]['categories_name'] . " > " . $cat_name;		
		$item_arr = $CATEGORY_ARR[$item_arr['parent_id']];
	}
	
	// Strip html from category name
	$cat_name = html_to_text($cat_name);
	
	return $cat_name;
}

function html_to_text($string){

	$search = array (
		"'<script[^>]*?>.*?</script>'si",  // Strip out javascript
		"'<[\/\!]*?[^<>]*?>'si",  // Strip out html tags
		"'([\r\n])[\s]+'",  // Strip out white space
		"'&(quot|#34);'i",  // Replace html entities
		"'&(amp|#38);'i",
		"'&(lt|#60);'i",
		"'&(gt|#62);'i",
		"'&(nbsp|#160);'i",
		"'&(iexcl|#161);'i",
		"'&(cent|#162);'i",
		"'&(pound|#163);'i",
		"'&(copy|#169);'i",
		"'&(reg|#174);'i",
		"'&#8482;'i",
		"'&#149;'i",
		"'&#151;'i",
		"'&#(\d+);'e"
		);  // evaluate as php
	
	$replace = array (
		" ",
		" ",
		"\\1",
		"\"",
		"&",
		"<",
		">",
		" ",
		"&iexcl;",
		"&cent;",
		"&pound;",
		"&copy;",
		"&reg;",
		"<sup><small>TM</small></sup>",
		"&bull;",
		"-",
		"uchr(\\1)"
		);
	
	$text = preg_replace ($search, $replace, $string);
	return $text;
	
}

function clean_description($string){

	$search = array (
		"'<html>'i",
		"'</html>'i",
		"'<body>'i",
		"'</body>'i",
		"'<head>.*?</head>'si",
		"'<!DOCTYPE[^>]*?>'si"
		); 
		
	$replace = array (
		"",
		"",
		"",
		"",
		"",
		""
		); 
		
	$text = preg_replace ($search, $replace, $string);
	return $text;

}

function build_str_key($text){
	
	$text = str_replace(" ", "-", trim(string_clean_search($text)));
	$text = rawurlencode(strtolower($text));
	
	$text = strtolower(clean_accents($text));
	
	return $text;
}

function clean_accents($text){

	$search = array (
		
		"'%C4%99'", #e
		"'%C3%A8'", #e
		"'%C3%A9'", #e
		"'%C3%AA'", #e
		"'%C3%AB'", #e
		"'%C3%89'", #e
		"'%C3%88'", #E
		"'%C3%8A'", #E
		
		"'%C4%85'", #a
		"'%C3%A3'", #a
		"'%C3%A0'", #a
		"'%C3%A4'", #a
		"'%C3%A2'", #a	
		"'%C3%A1'", #a
		"'%C3%A5'", #a
		"'%C3%81'", #A
		"'%C3%82'", #A
		"'%C3%84'", #A
		"'%C3%85'", #A
		"'%C3%80'", #A
		
		"'%C4%87'", #c
		"'%C3%A7'", #c
		"'%C3%87'", #C
		
		"'%C5%9B'", #s
		"'%C5%A1'", #s
		"'%C5%A0'", #S
		"'%C5%9A'", #S
		
		"'%C3%B0'", #d
		"'%C3%B1'", #n
		"'%C3%BD'", #y
		"'%C4%9F'", #g
		
		"'%C4%B1'", #i
		"'%C3%AE'", #i
		"'%C3%AD'", #i
		"'%C3%AF'", #i
		"'%C3%AC'", #i
		"'%C3%8D'", #I
		"'%C3%8E'", #I
		"'%C4%B0'", #I
		
		"'%C5%82'", #l
		
		"'%C5%84'", #n
		
		"'%C3%BA'", #u
		"'%C3%BB'", #u
		"'%C3%B9'", #u
		"'%C3%BC'", #u
		"'%C5%B1'", #u
		
		"'%C3%9C'", #U
		
		"'%C3%B4'", #o
		"'%C3%B3'", #o
		"'%C3%91'", #o
		"'%C3%B6'", #o
		"'%C5%91'", #o
		"'%C3%B2'", #o
		"'%C3%B5'", #o
		"'%C3%93'", #O
		"'%C3%96'", #O
		
		"'%C3%9F'", #ss
		"'%C5%BC'", #z
		"'%C5%BA'", #z
		"'%C5%BB'", #Z
		
		"'%C3%A6'", #ae
		"'%C3%B8'", #oe
		
		"'%C2%AE'",
		"'%C2%B4'",
		"'%E2%84%A2'",
		
	);
	
	$replace = array (
		
		"e",
		"e",
		"e",
		"e",
		"e",
		"e",
		"E",
		"E",
		
		"a",
		"a",
		"a",
		"a",
		"a",
		"a",
		"a",
		"A",
		"A",
		"A",
		"A",
		"A",
		
		"c",
		"c",
		"C",
		
		"s",
		"s",
		"S",
		"S",
		
		"d",
		"n",
		"y",
		"g",
		
		"i",
		"i",
		"i",
		"i",
		"i",
		"I",
		"I",
		"I",
		
		"l",
		
		"n",
		
		"u",
		"u",
		"u",
		"u",
		"u",
		
		"U",
		
		"o",
		"o",
		"o",
		"o",
		"o",
		"o",
		"o",
		"O",
		"O",
		
		"ss",
		"z",
		"z",
		"Z",
		
		"ae",
		"oe",
		
		"",
		"",
		"",
		
	);
	
	$text = preg_replace($search, $replace, $text);
	
	return $text;

}

// CLEANS STRINGS
function string_clean_search($string){
	
	$trans = get_html_translation_table(HTML_ENTITIES);
	$trans = array_flip ($trans);
	$string = strtr($string, $trans);
	
	$search = array (
		"'&quot;'",
		"'&lt;'",
		"'&gt;'",
		"'%&pound;'",
		"'%&euro;'",
		"'-'",
		"'~'",
		"'!'",
		"'\?'",
		"'@'",
		"'#'",
		"'\\$'",
		"'%'",
		"'\^'",
		"'&'",
		"'\*'",
		"'\('",
		"'\)'",
		"'_'",
		"'\+'",
		"'='",
		"'\.'",
		"','",
		"'\''",
		"'\['",
		"'\]'",
		"'{'",
		"'}'",
		"'\|'",
		"'\"'",
		"':'",
		"';'",
		"'/'",
		"'\\\'",
		"'>'",
		"'<'",		
		"'[\r]+'",
		"'[\n]+'",
		"'[\t]+'",
		"'[\s]+'",
	);
	
	$replace = array (
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
		" ",
	);
	
	$string = preg_replace($search, $replace, $string);
	
	return $string;
	
}

function replace_not_in_tags($find_str, $replace_str, $string) {	
	$find = array($find_str);
	$replace = array($replace_str);	
	preg_match_all('#[^>]+(?=<)|[^>]+$#', $string, $matches, PREG_SET_ORDER);	
	foreach ($matches as $val) {	
		if (trim($val[0]) != "") {
			$string = str_replace($val[0], str_replace($find, $replace, $val[0]), $string);
		}
	}	
	return $string;
}

function compression_start(){

	global $_SERVER, $_SVR;	
	$_SVR['NO_END_COMPRESSION'] = false;
	$_SVR['IDX_DO_GZIP_COMPRESS'] = false;
	
	// We have headers already sent so we cannot start the compression
	if (headers_sent()) {
		$_SVR['NO_END_COMPRESSION'] = true;
		return false;
	}
	
	$idx_phpver = phpversion();
	$useragent = (isset($_SERVER["HTTP_USER_AGENT"]) ) ? $_SERVER["HTTP_USER_AGENT"] : $HTTP_USER_AGENT;
	if ($idx_phpver >= "4.0.4pl1" && (strstr($useragent, "compatible") || strstr($useragent, "Gecko"))) {
		if (extension_loaded("zlib"))	{
			// SET COMPRESSION LEVEL
			ini_set("zlib.output_compression_level", 5);
			ob_start("ob_gzhandler");
		}
	}
	elseif ($idx_phpver > "4.0") {
	
		if (strstr($_SERVER['HTTP_ACCEPT_ENCODING'], "gzip")) {
		
			if (extension_loaded("zlib")) {
			
				// SET COMPRESSION LEVEL
				ini_set("zlib.output_compression_level", 5);
				$_SVR['IDX_DO_GZIP_COMPRESS'] = true;
				ob_start();
				ob_implicit_flush(0);
				header("Content-Encoding: gzip");
			}			
		}
	}
}

function compression_end(){

	global $_SERVER, $_SVR;
	
	// We have not started the compression as we have headers already sent
	if ($_SVR['NO_END_COMPRESSION']) {
		return false;
	}
	// COMPRESS BUFFERED OUTPUT IF REQUIRED AND SEND TO BROWSER
	if ($_SVR['IDX_DO_GZIP_COMPRESS']) {
		$gzip_contents = ob_get_contents();
		ob_end_clean();
		$gzip_size = strlen($gzip_contents);
		$gzip_crc = crc32($gzip_contents);
		$gzip_contents = gzcompress($gzip_contents, 9);
		$gzip_contents = substr($gzip_contents, 0, strlen($gzip_contents) - 4);
		print "\x1f\x8b\x08\x00\x00\x00\x00\x00";
		print $gzip_contents;
		print pack("V", $gzip_crc);
		print pack("V", $gzip_size);
	}
}

?>